<?php
/**
 * @property $_wsdlUrl
 *
 */
class Lib_Application_File_Soap_Transfer extends Zend_File_Transfer_Adapter_Abstract {

    /**
     *
     * @var string Путь к файлу wsdl
     */
    private $_wsdlUrl;

    private $_projectName;

    private $_projectArea;

    private $_fileId;

    private $_rewriteMode = false;

    private $_convertParams = array();

    //private $_fileName;

    private $_imageFormat = 'jpg';

    private $_rotate = 0;

    private $_crop = array();

    private $_sourceImageName;

    private $_sourceUrl;

    private $_config;

    private $_validator = false;

    private $_fileContent;

    private $_normalize;

    private $_unsharpmask;

    private $_saturation;

    private $_hue;

    /**
     * Устанавливает имя папки проекта
     * @param string $name - имя папки проекта
     * @return Image_Soap $this
     */
    public function setProjectName($name) {
        $this->_projectName = (string) $name;
        return $this;
    }

    /**
     *
     * @param string $area_name - имя папки категории
     * @return Image_Soap $this
     */
    public function setProjectArea($area_name) {
        $this->_projectArea = (string) $area_name;
        return $this;
    }

    /**
     *
     * @param integer $id - id файла
     * @return Image_Soap $this
     */
    public function setFileId($id) {
        $this->_fileId = (int) $id;
        return $this;
    }

    /**
     *
     * @param integer $mode - режим перезаписи
     * @return Image_Soap $this
     */
    public function setRewriteMode($mode) {
        $this->_rewriteMode = (int) $mode;
        return $this;
    }

    /**
     * Задает формат файла
     * @param string $format - формат
     * @return Image_Soap $this
     */
    public function setImageFormat($format) {
        $this->_imageFormat = (string) $format;
        return $this;
    }

    /**
     *
     * @param string $content - содержимое файла
     * @return Image_Soap $this
     */
    public function setImageContent($content) {
        $this->_fileContent = $content;
        return $this;
    }

    /**
     *
     * @param sting $imageSource - путь к файлу
     * @return Image_Soap $this
     */
    public function setImageSource($imageSource) {
        $this->_sourceImageName = (string) $imageSource;
        return $this;
    }

    /**
     *
     * @param sting $imageSource - URL к файлу
     * @return Image_Soap $this
     */
    public function setUrlSource($imageUrl) {
        $this->_sourceUrl = (string) $imageUrl;
        return $this;
    }

    public function __construct($projectName = null, $projectArea = null, $fileId = null, $attribute = array()) {

        if ( null !== $projectName ) {
            $this->setProjectName($projectName);
        }

        if ( null !== $projectArea ) {
            $this->setProjectArea($projectArea);
        }

        if ( null !== $fileId ) {
            $this->setFileId($fileId);
        }

        if ( isset($attribute['reWriteMode']) ) {
            $this->setRewriteMode($attribute['reWriteMode']);
        }

        if ( isset($attribute['imageFormat']) ) {
            $this->setImageFormat($attribute['imageFormat']);
        }

        $this->_config = Zend_Registry::getInstance()->get('config')->soap->image->toArray();

        if ( isset($this->_config['wsdl']) ) {
            $this->setWsdlUrl($this->_config['wsdl']);
        }

        $this->_prepareFiles();

//        $this->_setupValidators();
    }

    /**
     * Установка путя к файлу wsdl
     * @param string $url путь к файлу wsdl
     */
    public function setWsdlUrl($url) {
        $this->_wsdlUrl = (string) $url;
    }

    /**
     * Возвращает путь к wsdl файлу
     * @return string
     */
    public function getWsdlUrl() {
        return $this->_wsdlUrl;
    }


    /**
    * @author megadevel
    * @since 3 нояб. 2010
    * @param
    * @return
    */
    public function setCrop($top, $left, $weight, $height) {
        $this->_crop = array('top' => $top, 'left' => $left, 'weight' => $weight, 'height' => $height);
    }

    /**
    * @author megadevel
    * @since 3 нояб. 2010
    * @param
    * @return
    */
    public function setRotate($rotate=90) {
        $this->_rotate = $rotate;
    }




    /**
     * Метод шуршит переменную $_FILES. Теперь не нужно указывать файл ручками.
     */
    protected function _prepareFiles() {

    	$this->_files = array();
		if(!count($_FILES))return $this;

        foreach ($_FILES as $form => $content) {
            if (is_array($content['name'])) {
                foreach ($content as $param => $file) {
                    foreach ($file as $number => $target) {
                        $this->_files[$form . '_' . $number . '_'][$param]      = $target;
                        $this->_files[$form]['multifiles'][$number] = $form . '_' . $number . '_';
                    }
                }

                $this->_files[$form]['name'] = $form;
                foreach($this->_files[$form]['multifiles'] as $key => $value) {
                    $this->_files[$value]['options']   = $this->_options;
                    $this->_files[$value]['validated'] = false;
                    $this->_files[$value]['received']  = false;
                    $this->_files[$value]['filtered']  = false;

                    $mimetype = $this->_detectMimeType($this->_files[$value]);
                    $this->_files[$value]['type'] = $mimetype;

                    $filesize = $this->_detectFileSize($this->_files[$value]);
                    $this->_files[$value]['size'] = $filesize;

                    if ($this->_options['detectInfos']) {
                        $_FILES[$form]['type'][$key] = $mimetype;
                        $_FILES[$form]['size'][$key] = $filesize;
                    }
                }
            } else {
                $this->_files[$form]              = $content;
                $this->_files[$form]['options']   = $this->_options;
                $this->_files[$form]['validated'] = false;
                $this->_files[$form]['received']  = false;
                $this->_files[$form]['filtered']  = false;

                $mimetype = $this->_detectMimeType($this->_files[$form]);
                $this->_files[$form]['type'] = $mimetype;

                $filesize = $this->_detectFileSize($this->_files[$form]);
                $this->_files[$form]['size'] = $filesize;

                if ($this->_options['detectInfos']) {
                    $_FILES[$form]['type'] = $mimetype;
                    $_FILES[$form]['size'] = $filesize;
                }
            }
        }

        return $this;
    }


    /**
     * Валидация файла.
     * @param boolean
     */
    public function isValid($files = null) {
        $this->_validator = true;
        return parent::isValid($files);
    }

    /**
     *
     * @param <type> $options
     * @return boolean/string
     */
    public function send($options = null) {

        // проверяем наличие необходимых параметров
        $this->_validateParams();

        //если метод isValid не был вызван, то валидируем здесь
        if ( false == $this->_validator ) {
            if ( false == parent::isValid() ) {
                return false;
            }
        }

        $params = array(
                'projectName'  	=> $this->_projectName,
                'projectArea'  	=> $this->_projectArea,
                'imageFormat'  	=> $this->_imageFormat,
                'photoID'      	=> $this->_fileId,
                'convertParams'	=> $this->_convertParams,
                'reWriteMode'   => $this->_rewriteMode,
        );

        if ( isset($this->_fileContent) && ! isset($this->_sourceImageName) ) {
            $params['image'] = $this->_fileContent;
        }

        if ( ! isset($this->_sourceImageName) ) {
            $files = $this->getFileInfo();

            if ( is_array($files) ) {
                foreach ($files as $form => $file) {
                    if ( isset($file['tmp_name']) && is_string($file['tmp_name']) && strlen($file['tmp_name'])) {
                        $fp = file_get_contents($file['tmp_name']);
                        if ( false != $fp ) {
                            $params['image'] = $fp;
                        }
                    }
                }
            }
        }

        /**
         * Граблі, для урлів картінок
         */
        if (isset($this->_sourceUrl)){
            $fp = file_get_contents($this->_sourceUrl);
            if( false != $fp ) {
                $params['image'] = $fp;
            }
        }

        if ( isset($this->_sourceImageName) ) {
            $params['sourceImageName'] = $this->_sourceImageName;
        }

        if ( ! isset($params['image']) && ! isset($params['sourceImageName']) ) {
            throw new Zend_File_Transfer_Exception('Image not found');
        }

        $path = null;

        try {
//            $soap = new Zend_Soap_Client($this->_wsdlUrl);
            $soap = new \SoapClient($this->_wsdlUrl);
            $path = $soap->riaAddPhoto($params);

        } catch (Exception $e ) {
            throw new Zend_File_Transfer_Exception($e->getMessage());
        }

        return $path;
    }

    /**
     * Проверка необходимых параметров.
     */
    private function _validateParams() {

        if ( null === $this->_projectName ) {
            throw new Zend_File_Transfer_Exception('projectName empty');
        }

        if ( null === $this->_projectArea ) {
            throw new Zend_File_Transfer_Exception('projectArea empty');
        }

        if ( null === $this->_fileId ) {
            throw new Zend_File_Transfer_Exception('fileId empty');
        }

        if ( null === $this->_wsdlUrl || ! is_string($this->_wsdlUrl) ) {
            throw new Zend_File_Transfer_Exception('wsdlUrl not found');
        }

        if ( ! count($this->_convertParams) ) {
            throw new Zend_File_Transfer_Exception('convertParams are empty');
        }

    }


    /**
     * Редактирование фото
     * @return string $path
     */
    public function edit() {

        $this->_validateParams();

        $this->_imageFormat = 'jpeg';
        try {
            $soap = new \SoapClient($this->_wsdlUrl);
            $path = $soap->riaEditPhoto(array(
                    'projectName'   => $this->_projectName,
                    'projectArea'   => $this->_projectArea,
                    'imageFormat'   => $this->_imageFormat,
                    'photoID'       => $this->_fileId,
                    'convertParams' => $this->_convertParams,
                    'rotate'        => $this->_rotate,
                    'normalize'     => $this->_normalize,
                    'unsharpmask'   => $this->_unsharpmask
//                    'brightness'    => $this->_brightness,
//                    'saturation'    => $this->_saturation,
//                    'hue'           => $this->_hue,
                    //'crop'          => $this->_crop,
            ));

            return $path;
        } catch (Exception $e ) {
            throw new Zend_File_Transfer_Exception($e->getMessage());
        }
    }

    public function receive($options = null) {
        throw new Zend_File_Transfer_Exception('receive is not supported');
    }

    public function isSent($files = null) {
        throw new Zend_File_Transfer_Exception('isSent is not supported');
    }

    public function isReceived($files = null) {
        throw new Zend_File_Transfer_Exception('isReceived is not supported');
    }

    public function isUploaded($files = null) {
        throw new Zend_File_Transfer_Exception('isUploaded is not supported');
    }

    public function isFiltered($files = null) {
        throw new Zend_File_Transfer_Exception('isFiltered is not supported');
    }

    /**
     *
     * @param integer $maxWidth
     * @param integer $maxHeight
     * @param integer $addLetter
     * @param integer $method
     * @param integer $attribute
     */
    public function addConvertParam($maxWidth, $maxHeight, $addLetter, $method, $attribute = array()) {

        if ( isset($attribute['textParams']) && is_array($attribute['textParams']) ) {
            foreach ( $attribute['textParams'] as $param ) {
                if ( $param['x'] == '' || $param['y'] == '' || $param['text'] == '' ) {
                    throw new Zend_File_Transfer_Exception('textParams are empty');
                }
            }
        }

        $this->_convertParams[] = array(
                'maxWidth'		=> $maxWidth * 1,
                'maxHeight'		=> $maxHeight * 1,
                'addLetter'		=> $addLetter,
                'method'		=> $method * 1,
                'zoomIn'		=> ( isset($attribute['zoomIn']) ) 		? $attribute['zoomIn'] 		: null,
                'background'            => ( isset($attribute['background']) ) 	? $attribute['background'] 	: null,
                'quality' 		=> ( isset($attribute['quality']) ) 	? $attribute['quality'] 	: null,
                'imageFormat'           => ( isset($attribute['imageFormat']) ) ? $attribute['imageFormat'] : null,
                'unsharpmask'           => ( isset($attribute['unsharpmask']) ) ? $attribute['unsharpmask'] : null,
                'normalize'             => ( isset($attribute['normalize']) ) 	? $attribute['normalize'] 	: null,
                'textParams'            => ( isset($attribute['textParams']) ) 	? $attribute['textParams'] 	: null ,
        );

        return $this;
    }

    /**
     * Установка правил валидации для файла согласно конфиг файлу.
     */
    private function _setupValidators() {

        if (is_array($this->_config)) {

            if ( isset($this->_config['fileSize']['max']) ) {
                $fileSize['max'] = $this->_config['fileSize']['max'];
            }

            if ( !empty($this->_config->fileSize->min) ) {
                $fileSize['min'] = $this->_config->fileSize->min;
            }

            if ( count($fileSize) ) {
                $fileSize['bytestring'] = false;
                $this->addValidator('FilesSize', false, $fileSize);
            }

            if ( ! empty($this->_config->imageSize->minheight) ) {
                $imageSize['minheight'] = $this->_config->imageSize->minheight;
            }

            if ( ! empty($this->_config->imageSize->minwidth) ) {
                $imageSize['maxheight'] = $this->_config->imageSize->maxheight;
            }

            if ( ! empty($this->_config->imageSize->maxheight) ) {
                $imageSize['minwidth'] = $this->_config->imageSize->minwidth;
            }

            if ( ! empty($this->_config->imageSize->maxwidth) ) {
                $imageSize['maxwidth'] = $this->_config->imageSize->maxwidth;
            }

            if ( count($imageSize) ) {
                $this->addValidator('ImageSize', false, $imageSize);
            }

            if ( ! empty($this->_config->mime_types) ) {
                $mimeTypes = $this->_config->mime_types;

                $mimeTypes = explode(',', $mimeTypes);

                foreach ($mimeTypes as $type) {
                    $types[] = trim($type);
                }

                $this->addValidator('MimeType', false, $types);
            }
        }
    }



}